#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
int main(int argc, char *argv[])
{
    // 获取服务器的ip和端口
    if (argc != 3)
    {
        std::cerr << "usage: " << argv[0] << "server_ip server_port";
        return 1;
    }

    std::string server_ip = argv[1];
    u_int16_t server_port = std::stoi(argv[2]);

    struct sockaddr_in peer;
    // 清空sockaddr_in
    bzero(&peer, sizeof(peer));
    peer.sin_family = AF_INET;
    peer.sin_addr.s_addr = inet_addr(server_ip.c_str());
    peer.sin_port = htons(server_port);

    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "创建Socket失败！" << std::endl;
        return 1;
    }

    // 不用显式绑定ip和port 到Socket 采用随机端口方式

    while (true)
    {
        std::string send_message;
        // 从标准输出流中获取消息
        std::cout << "Please enter# ";
        std::getline(std::cin, send_message);
        // 发消息
        //std::cout << "发送消息：" << send_message << std::endl;
        int n = sendto(sockfd, send_message.c_str(), send_message.size(), 0, (sockaddr *)&peer, sizeof(peer));

        char message[1024];

        socklen_t peer_len = sizeof(peer);
        // 收消息
        int msg_len = recvfrom(sockfd, message, sizeof(message)-1, 0, (sockaddr *)&peer, &peer_len);
        if(msg_len < 0)
        {
            std::cerr<<"收消息出错！"<<std::endl;
            return 2;
        }
        message[msg_len] = 0;
        // 打印收到的消息
        std::cout << message << std::endl;
    }

    return 0;
}
